package com.hopoke.common.domain;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageDTO<T> {

    private Long total;

    private Long pageNum;

    private List<T> list;

    public static <T> PageDTO<T> empty(Long total, Long pages) {
        return new PageDTO<>(total, pages, Collections.emptyList());
    }
    public static <T> PageDTO<T> empty(Page<?> page) {
        return new PageDTO<>(page.getTotal(), page.getPages(), Collections.emptyList());
    }

    public static <VO, PO> PageDTO<VO> of (Page<PO> page, Class<VO> clazz) {

        List<PO> records = page.getRecords();

        if(records.isEmpty()) {
            return empty(page);
        }

        return new PageDTO<>(page.getTotal(), page.getCurrent(),
                BeanUtil.copyToList(records, clazz));
    }


    public static <VO, PO> PageDTO<VO> of (Page<PO> page, Function<PO, VO> convert) {

        List<PO> records = page.getRecords();
        if(records.isEmpty()) {
            return empty(page);
        }

        return new PageDTO<>(page.getTotal(), page.getCurrent(),
                records.stream().map(convert).collect(Collectors.toList()));
    }
}
